package MainApp;

import java.io.File;
import java.awt.Desktop;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import RMI.ReceiveMessageInterface;
import TagsDB.Plugin;
import TagsDB.TagedFile;

import com.cloudgarden.resource.SWTResourceManager;


/**
 * This code was edited or generated using CloudGarden's Jigloo
 * SWT/Swing GUI Builder, which is free for non-commercial
 * use. If Jigloo is being used commercially (ie, by a corporation,
 * company or business for any purpose whatever) then you
 * should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details.
 * Use of Jigloo implies acceptance of these licensing terms.
 * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
 * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
 * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class AppGUI extends org.eclipse.swt.widgets.Composite {


	private Menu menu1;
	private Button butChooseFolder;
	private Label labelStatus;
	private Text txtUserToShare;
	private Table tableResultSearch;
	private Label labelResultSearch;
	private Label labelChooseTags;
	private Text txtFileNameToSearch;
	private Label labelNameFileToSearch;
	private Button butSearch;
	private Table tableOptionSearch;
	private Label labelErrorNamePlugin;
	private Button butAddPlugin;
	private Text txtSelectedPath;
	private Label labelNamePlugin;
	private Text txtNamePlagin;
	private Table table1;
	private Button button1;
	private Composite composite2;
	private Button butPause;
	private Button butPlay;
	private Composite composite4;
	private Composite composite3;
	private TabItem tabItem2;
	private Button butShare;
	private Label labelUser;
	private Label labelFolderName;
	private Text txtFolderName;
	private Composite composite1;
	private TabItem tabItem1;
	private TabItem tabItem3;
	private MenuItem aboutMenuItem;
	private MenuItem contentsMenuItem;
	private Menu helpMenu;
	private MenuItem helpMenuItem;
	private TabFolder tabFolder2;
	private MenuItem exitMenuItem;
	private MenuItem closeFileMenuItem;
	private MenuItem saveFileMenuItem;
	private MenuItem newFileMenuItem;
	private MenuItem openFileMenuItem;
	private Menu fileMenu;
	private MenuItem fileMenuItem;
	private TabItem tabItem4;
	private TableItem item;
	private ReceiveMessageInterface rmiService;

	private String chooseFolderToShare(String mainFolder)
	{
		System.out.println("My main folder in the choose is :"+mainFolder);
		DirectoryDialog dd=new DirectoryDialog(getShell());
		String filterExt=mainFolder;
		dd.setFilterPath(filterExt);
		String selectedDir=dd.open();
		int lastLocation=selectedDir.lastIndexOf("\\");
		String path=selectedDir.subSequence(0, lastLocation).toString();
		System.out.println("The path is "+ path);
		if(path.equals(mainFolder))
		{
			return selectedDir.subSequence(lastLocation+1, selectedDir.length()).toString();
		}
		else
		{
			return null;
		}
	}
	private String choosePlugin()
	{

		FileDialog fd=new FileDialog(getShell(), SWT.OPEN);
		String[] filterExt={"*.class"};
		fd.setFilterExtensions(filterExt);
		fd.setText("Open");

		String selected=fd.open();
		System.out.println("mY selected folder is "+selected);
		/*  if(selected!=null)
  {
   if(txtNamePlagin.getText().isEmpty())
   {
    strPluginName=selected;
   }
   else
   {

    strPluginName=txtNamePlagin.getText();
   }
   System.out.println("go to add plug");
   ManagerAppGUI.getManagerAppGUIinstance().addPluginToDB(selected, strPluginName);

   refreshPlugin();
  }*/
		return selected;
	}
	private void refreshSearchResult(ArrayList<TagedFile> resArrayList)
	{
		tableResultSearch.removeAll();
		labelResultSearch.setVisible(false);
		tableResultSearch.setVisible(false);
		if(resArrayList==null)
		{
			return;
		}
		if(resArrayList.isEmpty())
		{
			labelResultSearch.setVisible(true);
			labelResultSearch.setText("Sorry,files not found");
			labelResultSearch.setForeground(SWTResourceManager.getColor(255, 0, 0));

		}
		else
		{
			labelResultSearch.setVisible(true);
			labelResultSearch.setText("The results are:");
			tableResultSearch.setVisible(true);
			for(TagedFile tf:resArrayList)
			{
				item=new TableItem(tableResultSearch, SWT.NULL);
				item.setText(tf.getFileName());
				item.setData(tf);
			}
		}
	}
	private void refreshPlugin() throws RemoteException
	{
		table1.removeAll();
		ArrayList<Plugin>plugins = (ArrayList<Plugin>) rmiService.getPlugins();
		System.out.println("----In refresh----");
		for(Plugin p:plugins)
		{

			item=new TableItem(table1, SWT.CHECK,SWT.NULL);
			if(p.getIsUse()==1)
			{
				item.setChecked(true);
			}
			else
			{
				item.setChecked(false);
			}
			item.setText(p.getNamePlugin());
		}
	}
	private void refreshOptionSearch() throws RemoteException
	{
		tableOptionSearch.removeAll();
		System.out.println("blala");
		ArrayList<String> options=rmiService.allOptionTags();//ManagerAppGUI.getManagerAppGUIinstance().allOptionTags();
		System.out.println("bloblbo "+options.size());

		for(String s:options)
		{
			System.out.println(s);
			item=new TableItem(tableOptionSearch, SWT.CHECK,SWT.NONE);
			item.setChecked(false);
			item.setText(s.toString());
		}

	}

	{
		//Register as a resource user - SWTResourceManager will
		//handle the obtaining and disposing of resources
		SWTResourceManager.registerResourceUser(this);
	}

	public AppGUI(Composite parent, int style) {
		super(parent, style);
		initGUI();
	}

	/**
	 * Initializes the GUI.
	 */
	private void initGUI() 
	{

		try {
			Registry registry=LocateRegistry.getRegistry("localhost");
			System.out.println("5-5-5-5-5-5-5-");
			rmiService=(ReceiveMessageInterface)(registry.lookup("serviceRMI"));
			this.setSize(new org.eclipse.swt.graphics.Point(500,400));
			this.setBackground(SWTResourceManager.getColor(192, 192, 192));
			this.setLayout(null);
			{
				System.out.println("before restore");
				rmiService.restorePlugin();
				//ManagerAppGUI.getManagerAppGUIinstance().restorePlugin();
				tabFolder2 = new TabFolder(this, SWT.NONE);
				{//Control panel
					tabItem2 = new TabItem(tabFolder2, SWT.NONE);
					tabItem2.setText("Control Panel");
					{
						composite4 = new Composite(tabFolder2, SWT.NONE);
						composite4.setLayout(null);
						tabItem2.setControl(composite4);
						{
							butPlay = new Button(composite4, SWT.PUSH | SWT.CENTER);
							butPlay.setImage(SWTResourceManager.getImage("images/play1-150x150.png"));
							butPlay.setBounds(31, 41, 39, 38);
							butPlay.addSelectionListener(new SelectionListener() {

								@Override
								public void widgetSelected(SelectionEvent arg0) 
								{
									boolean status;
									labelStatus.setVisible(true);
									try 
									{
										status = rmiService.playService();
										if(!status)
										{

											labelStatus.setText("Service already work");
											labelStatus.setForeground(SWTResourceManager.getColor(200, 0, 0));
										}
										else
										{
											labelStatus.setText("Service start working");
											labelStatus.setForeground(SWTResourceManager.getColor(0, 200, 0));
										}
									} 
									catch (RemoteException e) 
									{
										// TODO Auto-generated catch block
										e.printStackTrace();
									}


								}

								@Override
								public void widgetDefaultSelected(SelectionEvent arg0) {
									// TODO Auto-generated method stub

								}
							});
						}
						{
							butPause = new Button(composite4, SWT.TOGGLE | SWT.CENTER);
							butPause.setImage(SWTResourceManager.getImage("images/pause1-150x150.png"));
							butPause.setBounds(98, 41, 39, 38);
							butPause.addSelectionListener(new SelectionListener() {

								@Override
								public void widgetSelected(SelectionEvent arg0) {

									boolean status;
									try 
									{
										status = rmiService.pauseService();
										labelStatus.setVisible(true);
										if(!status)
										{
											labelStatus.setText("Service already pause");
											labelStatus.setForeground(SWTResourceManager.getColor(200, 0, 0));
										}
										else
										{
											labelStatus.setText("Service stop working");
											labelStatus.setForeground(SWTResourceManager.getColor(0, 200, 0));
										}
									} 
									catch (RemoteException e) 
									{
										// TODO Auto-generated catch block
										e.printStackTrace();
									}

								}

								@Override
								public void widgetDefaultSelected(SelectionEvent arg0) {
									// TODO Auto-generated method stub

								}
							});
						}
						{
							labelStatus = new Label(composite4, SWT.BORDER);
							labelStatus.setBounds(182, 41, 236, 30);
							labelStatus.setVisible(false);
						}
					}
				}
				{//Share
					tabItem3 = new TabItem(tabFolder2, SWT.NONE);
					tabItem3.setText("Share Folder");
					{
						composite1 = new Composite(tabFolder2, SWT.NONE);
						composite1.setLayout(null);
						tabItem3.setControl(composite1);
						{
							txtFolderName = new Text(composite1, SWT.BORDER);
							txtFolderName.setBounds(99, 36, 129, 20);
						}
						{
							labelFolderName = new Label(composite1, SWT.NONE);
							labelFolderName.setText("Folder Name:");
							labelFolderName.setBounds(21, 36, 78, 20);
						}
						{
							labelUser = new Label(composite1, SWT.NONE);
							labelUser.setText("Share Folder With: (Enter userName seprade by , )");
							labelUser.setBounds(21, 90, 315, 22);
						}

						{
							butShare = new Button(composite1, SWT.PUSH | SWT.CENTER);
							butShare.setText("Share Folder");
							butShare.setBounds(171, 271, 142, 30);
							butShare.addSelectionListener(new SelectionListener() {

								@Override
								public void widgetSelected(SelectionEvent arg0) 
								{
									// TODO Auto-generated method stub
									try {
										rmiService.takeUserToShare(txtUserToShare.getText(),txtFolderName.getText());
									} catch (RemoteException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
									//         String nameFoledr=txtFolderName.getText();
								}

								@Override
								public void widgetDefaultSelected(SelectionEvent arg0) {
									// TODO Auto-generated method stub

								}
							});

						}
						{
							txtUserToShare = new Text(composite1, SWT.MULTI | SWT.WRAP | SWT.BORDER);
							txtUserToShare.setBounds(21, 112, 445, 108);
						}
						{
							butChooseFolder = new Button(composite1, SWT.PUSH | SWT.CENTER);
							butChooseFolder.setText("open");
							butChooseFolder.setBounds(234, 34, 52, 26);
							butChooseFolder.addSelectionListener(new SelectionListener() {

								@Override
								public void widgetSelected(SelectionEvent arg0) {
									// TODO Auto-generated method stub
									try {
										String flag=chooseFolderToShare(rmiService.getFolderPath());
										if(flag==null)
										{
											txtFolderName.setText("Folder is invalid");
											butShare.setEnabled(false);
										}
										else
										{
											txtFolderName.setText(flag);
											butShare.setEnabled(true);
										}
									} catch (RemoteException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}

								@Override
								public void widgetDefaultSelected(SelectionEvent arg0) {
									// TODO Auto-generated method stub

								}
							});
						}
					}
				}
				{//Plugins
					tabItem1 = new TabItem(tabFolder2, SWT.NONE);
					tabItem1.setText("Plugins");
					{
						composite2 = new Composite(tabFolder2, SWT.NONE);
						composite2.setLayout(null);
						tabItem1.setControl(composite2);
						{
							button1 = new Button(composite2, SWT.PUSH | SWT.CENTER);
							button1.setText("Load new plugin");
							button1.setBounds(31, 28, 127, 30);
							button1.addSelectionListener(new SelectionListener() {

								@Override
								public void widgetSelected(SelectionEvent arg0)
								{

									String strPluginName=choosePlugin();
									System.out.println(" my path plugin "+strPluginName);
									if(strPluginName!=null)
									{
										txtSelectedPath.setText("");
										txtSelectedPath.setText(strPluginName);
									}

								}

								@Override
								public void widgetDefaultSelected(SelectionEvent arg0) {
									// TODO Auto-generated method stub

								}
							});
						}
						{

							table1 = new Table(composite2, SWT.CHECK | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
							table1.setBounds(283, 22, 168, 315);
							table1.setLinesVisible(false); 
							TableColumn tableColumn = new TableColumn(table1, SWT.NONE);
							tableColumn.setWidth(168);
							refreshPlugin();
							table1.addListener(SWT.Selection, new Listener() 
							{

								@Override
								public void handleEvent(Event event) 
								{
									if(event.detail==SWT.CHECK)
									{
										TableItem item=(TableItem)event.item;
										String strPluginName=item.getText();
										try {
											rmiService.updateUsePlugin(strPluginName, item.getChecked());
										} catch (RemoteException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										// ManagerAppGUI.getManagerAppGUIinstance().updateUsePlugin(strPluginName,item.getChecked());
									}

								}
							});

						}
						{
							txtNamePlagin = new Text(composite2, SWT.BORDER);
							txtNamePlagin.setBounds(37, 126, 155, 20);
						}
						{
							labelNamePlugin = new Label(composite2, SWT.NONE);
							labelNamePlugin.setText("Enter name plugin:");
							labelNamePlugin.setBounds(35, 104, 129, 22);
						}

						{
							txtSelectedPath = new Text(composite2, SWT.READ_ONLY | SWT.BORDER);
							txtSelectedPath.setBounds(31, 70, 161, 20);
						}
						{
							butAddPlugin = new Button(composite2, SWT.PUSH | SWT.CENTER);
							butAddPlugin.setText("Add plugin");
							butAddPlugin.setBounds(37, 167, 109, 30);
							butAddPlugin.addSelectionListener(new SelectionListener() {

								@Override
								public void widgetSelected(SelectionEvent arg0) 
								{
									String strNamePlugin;
									String strPathPlugin=txtSelectedPath.getText();
									if(txtNamePlagin.getText().isEmpty())
									{
										strNamePlugin=strPathPlugin;
									}
									else
									{
										strNamePlugin=txtNamePlagin.getText();
									}

									boolean flag;
									try {
										System.out.println("Name plugis is "+strNamePlugin+" and path is "+strPathPlugin);
										flag = rmiService.checkPluginExist(strNamePlugin);
										System.out.println("the flag is "+flag);
										if(flag)
										{
											rmiService.addPluginToDB(strPathPlugin, strNamePlugin);
											System.out.println("After adding to db plugins");
											//ManagerAppGUI.getManagerAppGUIinstance().addPluginToDB(strPathPlugin, strNamePlugin);
											refreshPlugin();
										}
										else
										{
											labelErrorNamePlugin.setVisible(true);
										}
										refreshOptionSearch();
									} 
									catch (RemoteException e) 
									{
										// TODO Auto-generated catch block
										e.printStackTrace();
									}//ManagerAppGUI.getManagerAppGUIinstance().checkPluginExist(strNamePlugin);

								}

								@Override
								public void widgetDefaultSelected(SelectionEvent arg0) {
									// TODO Auto-generated method stub

								}
							});
						}
						{
							labelErrorNamePlugin = new Label(composite2, SWT.NONE);
							labelErrorNamePlugin.setText("The plugin name is already exist");
							labelErrorNamePlugin.setBounds(12, 203, 180, 30);
							labelErrorNamePlugin.setVisible(false);
							labelErrorNamePlugin.setForeground(SWTResourceManager.getColor(255, 0, 0));
						}
					}
				}
				{//Search
					tabItem4 = new TabItem(tabFolder2, SWT.NONE);
					tabItem4.setText("Search");
					{
						composite3 = new Composite(tabFolder2, SWT.NONE);
						composite3.setLayout(null);
						tabItem4.setControl(composite3);
						{
							tableOptionSearch = new Table(composite3, SWT.CHECK |SWT.BORDER);
							tableOptionSearch.setBounds(19, 72, 174, 198);
							tableOptionSearch.setLinesVisible(false); 
							TableColumn tableColumn = new TableColumn(tableOptionSearch, SWT.NONE);
							tableColumn.setWidth(174);
							System.out.println("before refresh the options serach");
							refreshOptionSearch();
							tableOptionSearch.addListener(SWT.Selection, new Listener() 
							{

								@Override
								public void handleEvent(Event event) 
								{
									if(event.detail==SWT.CHECK)
									{
										TableItem item=(TableItem)event.item;
										String strSearchName=item.getText();
										try {
											rmiService.optionsForSearch(item.getChecked(), strSearchName);
										} catch (RemoteException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										//ManagerAppGUI.getManagerAppGUIinstance().optionsForSearch(item.getChecked(), strSearchName);
									}

								}
							});
						}
						{
							butSearch = new Button(composite3, SWT.PUSH | SWT.CENTER);
							butSearch.setText("Search");
							butSearch.setBounds(59, 282, 60, 30);
							butSearch.addSelectionListener(new SelectionListener() {

								@Override
								public void widgetSelected(SelectionEvent arg0) 
								{
									String strFileName=txtFileNameToSearch.getText();
									ArrayList<String> tempOptions;
									try {
										//ManagerAppGUI.getManagerAppGUIinstance().getOptionsToSearch();
										tempOptions = rmiService.getOptionsToSearch();
										ArrayList<TagedFile> resArrayList=rmiService.search(strFileName, tempOptions);//ManagerAppGUI.getManagerAppGUIinstance().search(strFileName,tempOptions);
										refreshSearchResult(resArrayList);
									} catch (RemoteException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}



								}

								@Override
								public void widgetDefaultSelected(SelectionEvent arg0) {
									// TODO Auto-generated method stub

								}
							});
						}
						{
							labelNameFileToSearch = new Label(composite3, SWT.NONE);
							labelNameFileToSearch.setText("Enter the file name to search:");
							labelNameFileToSearch.setBounds(19, 16, 164, 20);
						}
						{
							txtFileNameToSearch = new Text(composite3, SWT.BORDER);
							txtFileNameToSearch.setBounds(183, 16, 192, 20);
						}
						{
							labelChooseTags = new Label(composite3, SWT.NONE);
							labelChooseTags.setText("Choose tags to search:");
							labelChooseTags.setBounds(19, 52, 149, 22);
						}
						{
							labelResultSearch = new Label(composite3, SWT.NONE);
							labelResultSearch.setBounds(259, 52, 185, 20);
							labelResultSearch.setVisible(false);
						}
						{
							tableResultSearch = new Table(composite3, SWT.BORDER);
							tableResultSearch.setBounds(285, 72, 174, 198);
							tableResultSearch.setVisible(false);
							tableResultSearch.addSelectionListener(new SelectionListener() {

								@Override
								public void widgetSelected(SelectionEvent arg0)
								{
									//noting -one click mouse
								}

								@Override
								public void widgetDefaultSelected(SelectionEvent arg0)
								{
									// double mouse click
									int itemIndex=tableResultSearch.getSelectionIndex();
									TableItem resItem= tableResultSearch.getItem(itemIndex);
									TagedFile t=(TagedFile)resItem.getData();
									String strPathFile=t.getFilePath();
									File file=new File(strPathFile);
									if (Desktop.isDesktopSupported())
									{
										try 
										{
											Desktop.getDesktop().open(file);
										} 
										catch (IOException e) 
										{

											e.printStackTrace();
										}
									} 
									else 
									{
										System.out.println("Awt Desktop is not supported!");
									}

								}
							});
						}
					}
				}

				tabFolder2.setBounds(0, 0, 500, 400);
				tabFolder2.setSelection(0);
			}
			{
				menu1 = new Menu(getShell(), SWT.BAR);
				getShell().setMenuBar(menu1);
				{
					fileMenuItem = new MenuItem(menu1, SWT.CASCADE);
					fileMenuItem.setText("File");
					{
						fileMenu = new Menu(fileMenuItem);
						{
							openFileMenuItem = new MenuItem(fileMenu, SWT.CASCADE);
							openFileMenuItem.setText("Open");
						}
						{
							newFileMenuItem = new MenuItem(fileMenu, SWT.CASCADE);
							newFileMenuItem.setText("New");
						}
						{
							saveFileMenuItem = new MenuItem(fileMenu, SWT.CASCADE);
							saveFileMenuItem.setText("Save");
						}
						{
							closeFileMenuItem = new MenuItem(fileMenu, SWT.CASCADE);
							closeFileMenuItem.setText("Close");
						}
						{
							exitMenuItem = new MenuItem(fileMenu, SWT.CASCADE);
							exitMenuItem.setText("Exit");
						}
						fileMenuItem.setMenu(fileMenu);
					}
				}
				{
					helpMenuItem = new MenuItem(menu1, SWT.CASCADE);
					helpMenuItem.setText("Help");
					{
						helpMenu = new Menu(helpMenuItem);
						{
							contentsMenuItem = new MenuItem(helpMenu, SWT.CASCADE);
							contentsMenuItem.setText("Contents");
						}
						{
							aboutMenuItem = new MenuItem(helpMenu, SWT.CASCADE);
							aboutMenuItem.setText("About");
						}
						helpMenuItem.setMenu(helpMenu);
					}
				}
			}
			this.layout();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * Auto-generated main method to display this 
	 * org.eclipse.swt.widgets.Composite inside a new Shell.
	 */
	public static void main(String[] args) 
	{
		Display display = Display.getDefault();
		Shell shell = new Shell(display);
		File f=new File("C://ourDropBox//User//ClientDetails.xml");

		if(f.exists())
		{
			AppGUI inst = new AppGUI(shell, SWT.NULL);
			Point size = inst.getSize();
			shell.setLayout(new FillLayout());
			shell.layout();
			if(size.x == 0 && size.y == 0) {
				inst.pack();
				shell.pack();
			} else {
				Rectangle shellBounds = shell.computeTrim(0, 0, size.x, size.y);
				shell.setSize(shellBounds.width, shellBounds.height);
			}
			shell.open();
			while (!shell.isDisposed()) {
				if (!display.readAndDispatch())
					display.sleep();
			}
			if(shell.isDisposed())
			{
				System.out.println("close me?");
				try {
					inst.rmiService.clearOptionsToSearch();
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		else
		{
			MessageBox messageBox = new MessageBox(shell, SWT.ERROR);
			messageBox.setMessage("Please install software before");
			int rc = messageBox.open();
		}
	}

}